<?php

class Heap
{
	private $db;
	private $table;
	public function __construct(){
		$this->db=sql::getIns();
		$cfg=cfg::getIns();
		$this->table=$cfg->heap_table;
	}
	
	public function add($k,$v,$t=0)
	{
		$sql="insert into {$this->table} values ('{$k}','{$v}',".($t!=0?time()+$t:$t).")";
		return $this->db->set_query($sql);
		//return $this->db->insert($this->table,array('key'=>$k,'value'=>$v,'expired'=>$t!=0?time()+$t:$t));
	}
	public function get($k)
	{
		$one=$this->db->getRow("select value,expired from {$this->table} where `key`='{$k}'");
		if(!$one)
		{
			return false;
		}
		if(time()>$one['expired'])
		{
			$this->db->delete("`key`='{$k}'",$this->table);
			return false;
		}
		else
		{
			return $one['value'];
		}
	}
	public function replace($k,$v,$t=0)
	{
		return $this->db->updatebyattr($this->table,array('value'=>$v,'expired'=>$t!=0?time()+$t:$t),'`key`',$k);
	}
	public function set($k,$v,$t=0)
	{
		if($this->get($k)===false)
		{
			return $this->add($k,$v,$t=0);
		}
		else
		{
			return $this->db->updatebyattr($this->table,array('value'=>$v,'expired'=>$t!=0?time()+$t:$t),'`key`',$k);
		}
	}
	public function del($k)
	{
		$this->db->delete("`key`='{$k}'",$this->table);
	}



	public function getStats($list='')
	{
		
	}

	public function getExtendedStats($list='')
	{
		
	}

	public function getVer()
	{
		
	}

	public function getAllKeys()
	{
		
	}
}